package priv.mill.server;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class MyClassLoader extends ClassLoader {
    public MyClassLoader() {
    }
    public Class<?> findClass(String name) throws ClassNotFoundException {
        String classPath = MyClassLoader.class.getResource("/").getPath();
        String fileName = name.replace(".", "/") + ".class";
        File classFile = new File(classPath, fileName);
        if(!classFile.exists()) {
            throw new ClassNotFoundException(classFile.getPath() + " 不存在");
        } else {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ByteBuffer bf = ByteBuffer.allocate(1024);
            FileInputStream fis = null;
            FileChannel fc = null;

            try {
                fis = new FileInputStream(classFile);
                fc = fis.getChannel();

                while(fc.read(bf) > 0) {
                    bf.flip();
                    bos.write(bf.array(), 0, bf.limit());
                    bf.clear();
                }
            } catch (FileNotFoundException var20) {
                var20.printStackTrace();
            } catch (IOException var21) {
                var21.printStackTrace();
            } finally {
                try {
                    fis.close();
                    fc.close();
                } catch (IOException var19) {
                    var19.printStackTrace();
                }

            }

            return this.defineClass(name,bos.toByteArray(), 0, bos.toByteArray().length);
        }
    }
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
		MyClassLoader myClassLoader = new MyClassLoader();
		Class<?> loadClass = myClassLoader.loadClass("priv.mill.servlet.SearchDemo");
		System.out.println(loadClass.newInstance());
	}
}
